package org.groupg.practice;

import com.opencsv.CSVWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * CSV操作演示主类
 */
public class CsvDemoApplication {
    private static final Logger logger = LoggerFactory.getLogger(CsvDemoApplication.class);

    public static void main(String[] args) {
        try {
            logger.info("=============== CSV操作演示开始 ===============");

            // 1. 基础写入/读取演示
            demoBasicCsvOperations();

            // 2. 高级格式处理演示
            demoAdvancedCsvOperations();

            // 3. 大型文件处理演示
            demoLargeFileProcessing();

            logger.info("=============== CSV操作演示完成 ===============");
        } catch (Exception e) {
            logger.error("应用程序执行失败", e);
        }
    }

    private static void demoBasicCsvOperations() {
        logger.info("----- 基础CSV操作演示开始 -----");

        // 准备数据
        List<Person> persons = new ArrayList<>();
        persons.add(new Person("张三", 28, "zhangsan@example.com"));
        persons.add(new Person("李四", 32, "lisi@example.com"));
        persons.add(new Person("王五", 25, "wangwu@example.com"));

        // 写入CSV - 使用自定义分隔符(竖线)和行结束符(Windows格式)
        String filePath = "people.csv";
        CsvWriterUtil.writeCsv(filePath, persons, '|', "\r\n");

        // 读取CSV - 跳过标题行(1行)
        List<Person> result = CsvReaderUtil.readCsv(filePath, '|', 1, Person.class);

        // 验证结果
        logger.info("读取结果验证:");
        result.forEach(person -> logger.info(">> {}", person));

        logger.info("----- 基础CSV操作演示结束 -----\n");
    }

    private static void demoAdvancedCsvOperations() {
        logger.info("----- 高级CSV操作演示开始 -----");

        // 1. 自定义格式写入
        String customFile = "custom_products.csv";
        AdvancedCsvProcessor.writeWithCustomFormat(customFile, '|', '"', '\\', "\r\n");

        // 2. 追加数据到CSV
        List<String[]> newRecords = Arrays.asList(
            new String[]{"P-1005", "Gaming Mouse", "45.99", "电竞鼠标|16000DPI"},
            new String[]{"P-1006", "USB-C Hub", "32.50", "多功能扩展坞\n支持4K输出"}
        );
        AdvancedCsvProcessor.appendToCsv(customFile, newRecords, '|');

        logger.info("----- 高级CSV操作演示结束 -----\n");
    }

    private static void demoLargeFileProcessing() {
        logger.info("----- 大型文件处理演示开始 -----");

        // 生成大型CSV文件（模拟）
        String largeFilePath = "large_dataset.csv";
        generateLargeCsvFile(largeFilePath, 5000);

        // 流式处理大型文件
        AdvancedCsvProcessor.processLargeCsv(largeFilePath, ',', 1000);

        logger.info("----- 大型文件处理演示结束 -----\n");
    }

    /**
     * 生成大型CSV文件（用于演示）
     * @param filePath 文件路径
     * @param recordCount 记录数量
     */
    private static void generateLargeCsvFile(String filePath, int recordCount) {
        logger.info("开始生成大型CSV文件: {} 条记录", recordCount);

        try (CSVWriter writer = new CSVWriter(new FileWriter(filePath))) {
            // 写入标题
            writer.writeNext(new String[]{"ID", "Name", "Value", "Category", "Description"});

            // 生成数据
            for (int i = 1; i <= recordCount; i++) {
                String[] record = {
                    "ID-" + i,
                    "Product_" + i,
                    String.valueOf(10 + (i % 100)),
                    i % 2 == 0 ? "Electronics" : "Home",
                    "Description for product #" + i
                };
                writer.writeNext(record);

                // 每1000条记录记录一次进度
                if (i % 1000 == 0) {
                    logger.debug("已生成 {} 条记录", i);
                }
            }

            logger.info("成功生成大型CSV文件: {} 条记录", recordCount);
        } catch (Exception e) {
            logger.error("生成大型CSV文件失败", e);
        }
    }
}
